<?php

function Harvest($bot)
{
    //getting plugin configurations
    $data = $bot->ld->GetPlSettings("cropsplugin");
    if (!isset($data)) return;

    $NoHarvestIfFull = 0;
    if (isset($data->NoHarvestIfFull)) { if ($data->NoHarvestIfFull == "1") {   $NoHarvestIfFull = 1; } }

    $StopHarvest = 0;
    if($bot->Goods >= ($bot->MaxGoods * 0.9))
    {
      if($NoHarvestIfFull == 1)
      {
        $StopHarvest = 1;
        $bot->SendMsg('[CROPS-Harvesting] Goods storage > 90% Full. Skipping Harvesting action.' .$bot->Goods ."/".$bot->MaxGoods);
        return;
      }
    }

    if (isset($data->collectcrop) && ($data->collectcrop == "1"))
    {
      $bot->SendMsg('=====================================');
      $bot->SendMsg('[CROPS-Harvesting] Action started...');
      //$bot->ReloadConfig();

      //========================================================================
      if ($data->clearWithered == "1" )
      {
        if ($bot->EternalFountain==true)
        {
          $bot->SendMsg('[CROPS-Harvesting] Eternal Fountain found. Skiping Withered crops.');
        }
        else
        {
          $reload = 0;
          foreach ($bot->fobjects as $obj)
          {
            if (($obj["className"] == "Plot") && ($obj["state"] == "withered") )
            {
              //$bot->SendMsg('Withered.' .$obj["id"]);
              $obj["state"] = "plowed";
              $bot->harvestAction($obj, "clear", "Crop");
                $reload++;
                //check for streakbonus
                if(isset($data->ALLbonus) && ($data->ALLbonus == "1"))
                $bot->streakBonus3();
              if (isset($bot->error_msg)) { $bot->ReloadConfig(); $reload = 0;}
            }
          }
		  if($reload > 0) $bot->fobjects = $bot->LoadWorldObjects("world_main");
        }
      }

      //========================================================================
      if ($StopHarvest == 0)
      {
        //$reload = 0;
        //$bot->SendMsg('[CROPS-Harvesting] Harvesting Crops');
        if(count($data->collectCropsData) ==0)
        {
          $bot->SendMsg('[CROPS-Harvesting] You did not select any crops in Crops Plugins. Skipping Harvesting action.');
          return;
        }
		$reload = 0;
        $cnt = 0;
        foreach ($bot->fobjects as $obj)
        {

          if ($obj["className"] == "Plot")
          {
            //fix by Tonycell
            //Now work with Eternal Fountain
            if (($obj["state"] == "withered") && ($bot->EternalFountain==true)) { $obj["state"] = "grown"; }

            if (($obj["state"] != "withered") && ($obj["state"] != "plowed") && in_array($obj["contractName"], $data->collectCropsData))
            {
              if ($obj["state"] == "grown")
              {
                $obj["state"] = "grown";
                $bot->harvestAction($obj, "harvest", "Crop");
                $reload++;
                //check for streakbonus
                if(isset($data->ALLbonus) && ($data->ALLbonus == "1"))
                $bot->streakBonus3();


                //checking amount ...
                $d = $tmp->_bodys[0]->_value['data'][0]['data']['doobers'];
                if(isset($d) && is_array($d) && (count($d) > 0))
                {
                  foreach($d as $doober) 
                  { 
				    // of goods collected
				    if($doober[0] == "goods")
					{
					  $cnt += (int)$doober[1];
                        if(($bot->Goods+$cnt) >= ($bot->MaxGoods * 0.9))
                        {
                            $StopHarvest = 1;
                            $bot->SendMsg('[CROPS-Harvesting] Goods storage > 90% Full. Stopping Harvesting action.' .$bot->Goods ."/".$bot->MaxGoods);
                            break 1; //breaks ->foreach ($bot->fobjects as $obj)
                        }
                        else
                        {
                        $bot->SendMsg('[CROPS-Harvesting] Goods: '.$bot->Goods .'+'.$cnt.'='.($bot->Goods+$cnt));
                        }
					}	
						
					// of premium goods collected	
					if($doober[0] == "premium_goods")
					{
					  $cnt += (int)$doober[1];
					    if(($bot->PremiumGoods+$cnt) >= ($bot->PremiumGoodsMax * 0.9))
                        {
                            $StopHarvest = 1;
                            $bot->SendMsg('[CROPS-Harvesting] Premium Goods storage > 90% Full. Stopping Harvesting action.' .$bot->PremiumGoods ."/".$bot->PremiumGoodsMax);
                            break 1; //breaks ->foreach ($bot->fobjects as $obj)
                        }
                        else
                        {
                        $bot->SendMsg('[CROPS-Harvesting] Premium Goods: '.$bot->PremiumGoods .'+'.$cnt.'='.($bot->PremiumGoods+$cnt));
                        }
					}	
				  } //foreach
                }
                if (isset($bot->error_msg)) { $bot->ReloadConfig(); break; }
              }//
            }
          }
        }
      }
      $bot->SendMsg('[CROPS-Harvesting] Action done.');
	  if($reload > 0) $bot->fobjects = $bot->LoadWorldObjects("world_main");
	}
} //end Harvest function

function Seed($bot)
{
  $data = $bot->ld->GetPlSettings("cropsplugin");
  if (!isset($data)) return;

  if (isset($data->seedlist) && (count($data->seedlist)>0))
  {
    $bot->SendMsg('=====================================');
    $bot->SendMsg('[CROPS-Planting] Action started...');
    //$bot->ReloadConfig();
    $good = true;

    //======================================================================
    if (isset($data->seedlist[0]))
    {
      $tmp = explode(' | ', $data->seedlist[0]);
      $cnt = $tmp[1];
      $sname = $tmp[0];
    }
    else
    {
      $good = false;
      $bot->SendMsg('[CROPS-Planting] There are no tasks.');
    }
    //======================================================================
    if ($good)
    {
      foreach ($bot->fobjects as $obj)
      {
        if ($cnt <= 0) break;
        if (($obj["className"] == "Plot") && ($obj["state"] == "plowed"))
        {
          $bot->startContract($obj, "plot_crop", $sname, "Crop");
          $cnt = $cnt - 1;
          if (isset($bot->error_msg)) { $bot->ReloadConfig(); $cnt += 1;}
        }
      }
      if ($cnt == 0)
      {
        unset($data->seedlist[0]);
        $data->seedlist = array_values($data->seedlist);
        $bot->ld->ExecQuery("update plugin_settings set value='" . serialize($data) . "' where plname='cropsplugin'");
      }
      else
      {
        $data->seedlist[0] = $sname . " | " . $cnt;
        $bot->ld->ExecQuery("update plugin_settings set value='" . serialize($data) . "' where plname='cropsplugin'");
      }
      $bot->pm->RefreshMePlugin("Crops");
    }
    $bot->SendMsg('[CROPS-Planting] Action done.');
  }
} //end Seed function

//=========== Greenhouse Grassroots Collect===============================================================
   function harvestGrassroots($bot)
{
    $data = $bot->ld->GetPlSettings("cropsplugin");
	  if (!isset($data)) return;
	  
	  if(isset($data->collectgreenHouse))
   {
      if($data->collectgreenHouse == "1")
      {
	     $reload = 0;
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[CROPS-GH-HARVEST] Action started...');
		 
		 if(count($data->collectgreenHouseIN) == 0)
            $bot->SendMsg(' *** You did not select any Greenhouse.');
				 
         if($bot->energy <= 0)
            $bot->CheckEnergy();//Check if has energy on iventory;
         if($bot->energy > 0)
         {
          //foreach($bot->fobjects as $obj)
			foreach ($data->collectgreenHouseIN as $id) //collect in rounds 
			{
			   $obj = $bot->fobjects["w$id"];
			   if($obj["className"] == "GreenHouse")
                  {
				   if (($obj['mechanicData']['greenHouseStorage']['item']['state'] == "withered") && ($bot->EternalFountain==true)) { $obj['mechanicData']['greenHouseStorage']['item']['state'] = "grown"; }
				    {
				     if ($obj['mechanicData']['greenHouseStorage']['item']['state'] == "grown")
					 {
					 $obj['mechanicData']['greenHouseStorage']['item']['state'] = "grown";
				     $bot->SendMsg('[CROPS-GH-HARVEST] ' . $obj['itemName'] . ' (ID:' . $obj["id"] . ')  harvest: ' . $obj['mechanicData']['greenHouseStorage']['item']['contractName']);
					 $bot->ObjectActionCrop($id, "greenHouseHarvest", "GMPlay", "", "GreenHouse", $obj);
					 $reload++;
                     //check for streakbonus
                     if(isset($data->ALLbonus) && ($data->ALLbonus == "1"))
                     $bot->streakBonus3();
					 }
					} 
                  }
                  if(isset($bot->error_msg))
                  {
                     $bot->ReloadConfig();$reload = 0;
                     $hasenergy = $bot->CheckEnergy();
                     if(($hasenergy == 0) && ($bot->Energy == 0))                       {break;}
                  }
            }//foreach
         }
         else
         {
            $bot->SendMsg('[CROPS-GH-HARVEST] No energy to harvest the Greenhouses');
         }

         $bot->SendMsg('[CROPS-GH-HARVEST] Action done.');
		 if($reload > 0)   { $bot->fobjects = $bot->LoadWorldObjects("world_main"); }
      }
   }
    }
	
	//=========== Greenhouse Grassroots Clear===============================================================
   function clearGrassroots($bot)
{
    $data = $bot->ld->GetPlSettings("cropsplugin");
	  if (!isset($data)) return;
	  
	  if(isset($data->clearGreenHouse))
   {
      if($data->clearGreenHouse == "1")
      {
	     $reload = 0;
         $bot->SendMsg('=====================================');
         $bot->SendMsg('[CROPS-GH-PLOW] Action started...');
		 
		if ($bot->EternalFountain==true)
        {
          $bot->SendMsg('[CROPS-GH-PLOW] Eternal Fountain found. Skiping Withered crops.');
        }
        else
		 {
		 
		 if(count($data->collectgreenHouseIN) == 0)
            $bot->SendMsg(' *** You did not select any Greenhouse.');
				 

          //foreach($bot->fobjects as $obj)
			foreach ($data->collectgreenHouseIN as $id) //collect in rounds 
			{
			   $obj = $bot->fobjects["w$id"];
			   if(($obj["className"] == "GreenHouse") && ($obj['mechanicData']['greenHouseStorage']['item']['state'] == "withered"))
                  {
				     $bot->SendMsg('[CROPS-GH-PLOW] ' . $obj['itemName'] . ' (ID:' . $obj["id"] . ')  plowing: ' . $obj['mechanicData']['greenHouseStorage']['item']['contractName']);
					 $bot->ObjectActionCrop($id, "greenHouseClear", "GMPlay", "", "GreenHouse", $obj);
					 $reload++;
                     //check for streakbonus
                     if(isset($data->ALLbonus) && ($data->ALLbonus == "1"))
                     $bot->streakBonus3();
                  }
                  if(isset($bot->error_msg))
                  {
                     $bot->ReloadConfig();$reload = 0;
                  }
            }//foreach


         $bot->SendMsg('[CROPS-GH-PLOW] Action done.');
		 if($reload > 0)   { $bot->fobjects = $bot->LoadWorldObjects("world_main"); }
		} 
      }
   }
 }
//=========== Greenhouse Grassroots Seed===============================================================
   function SeedGrassroots($bot)
{
    $data = $bot->ld->GetPlSettings("cropsplugin");
	  if (!isset($data)) return;
	  
    if(isset($data->seedgreenHouse) && isset($data->contractIN_))
   {
      if($data->seedgreenHouse == "1")
      {
	  	 $reload = 0;
	     $bot->SendMsg('[CROPS-GH-SEED] Action started...');

	  
	     if(count($data->collectgreenHouseIN) == 0)
         $bot->SendMsg(' *** You did not select any Greenhouse.');
	  
       //foreach($bot->fobjects as $obj)
		 foreach ($data->collectgreenHouseIN as $id) //collect in rounds
         {
		    $obj = $bot->fobjects["w$id"];
            if(($obj["className"] == "GreenHouse") && ($obj['mechanicData']['greenHouseStorage']['item']['state'] == "plowed"))
            {
            $bot->ObjectActionCrop($id, "greenHouseStorage", "catalogPurchase", $data->contractIN_, "GreenHouse", $obj);
            }
            if(isset($bot->error_msg))              {$bot->ReloadConfig();}
         }
		 $bot->SendMsg('[CROPS-GH-SEED] Action done.');
      }
   }  
        } 
	 

$this->AddHook('start_crops', 'ExecPlugin');
function ExecPlugin($bot)
{
   if ($bot->firstrun)
   { //not work if it's first bot cycle
     //$Name = "cropsplugin"; $Version = "0.4"; $Date = "2011-01-08";
     //$bot->ld->UpdatePluginVersion($bot, $Name, $Version, $Date )  ;
     return;
   }

   $msg  = $bot->irc('u').$bot->irc('b');
   $msg .= $bot->irc('cc').'2';
   $msg .= $bot->irc('ff').'13,5'.chr(232).$bot->irc('ff').'14,5';
   $msg .= 'Starting Plugin: CROPS';
   $bot->SendMsg($msg);

   Harvest($bot);
   Seed($bot);
   clearGrassroots($bot);
   harvestGrassroots($bot);
   SeedGrassroots($bot);
}
?>